const fs = require('fs');
const path = require('path');

/**
 * 根据提供的配置，扫描路由目录并生成路由地图文件。
 * @param {import('./types').ProRouterConfig} config - 已加载的配置对象。
 */
function buildRoutes(config) {
  console.log('Building route map...');
  try {
    if (!fs.existsSync(config.routersPath)) {
      console.warn(`[Nexora] Warning: Routers directory not found at ${config.routersPath}`);
      return;
    }

    const subdirectories = fs
      .readdirSync(config.routersPath, { withFileTypes: true })
      .filter((dirent) => dirent.isDirectory())
      .map((dirent) => dirent.name);

    const routeImports = [];
    const routeMapEntries = [];
    const outputDir = path.dirname(config.outputPath);
    fs.mkdirSync(outputDir, { recursive: true });

    for (const dir of subdirectories) {
      const indexPath = path.join(config.routersPath, dir, 'index.js');
      if (fs.existsSync(indexPath)) {
        const routeName = dir;
        const relativePath = path.relative(outputDir, indexPath)
                                 .replace(/\\/g, '/') // 兼容 Windows
                                 .replace('.js', '');

        routeImports.push(`const ${routeName}Router = require('./${relativePath}');`);
        routeMapEntries.push(`  '/${routeName}': ${routeName}Router,`);
      }
    }

    const fileContent = `// This file is auto-generated by Nexora. Do not edit manually.
// Timestamp: ${new Date().toISOString()}

${routeImports.join('\n')}

const routeMap = {
${routeMapEntries.join('\n')}
};

module.exports = routeMap;
`;
    fs.writeFileSync(config.outputPath, fileContent);
    console.log(`[Nexora] Route map successfully generated at ${config.outputPath}`);
  } catch (error) {
    console.error('[Nexora] Error generating route map:', error);
  }
}

module.exports = { buildRoutes };